package com.alog.yzd.jdbc.hm;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils2 {
    private static final String MYSQL_DRIVER = "com.mysql.cj.jdbc.Driver";
    //private static MyDataSource dataSource = null;
    private static DataSource dataSource = null;
    private JdbcUtils2(){}

    static {
        try {
            //自己实现的DataSource
//            Class.forName(MYSQL_DRIVER);
//            dataSource = new MyDataSource();

            //DBCP
            Properties prop = new Properties();
            prop.load(new FileInputStream("dbcp.properties"));
            dataSource = BasicDataSourceFactory.createDataSource(prop);

        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Connection getConnction() throws SQLException {
        return dataSource.getConnection();
    }

    public static DataSource getDataSource(){
        return dataSource;
    }
    public static void release(ResultSet rs, Statement st, Connection conn){
        try {
            if(rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                //为保持用户习惯, 用代理写了MyConnection类, 保持用户COnnection的使用习惯
                try {
                    if(conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
